package com.hat.easyexcel_export.excel;


import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.fastjson.JSONObject;
import com.hat.easyexcel_export.entity.MonPoint;
import org.apache.poi.ss.usermodel.*;


/**
 * @Description 行拦截器 将字符串的经纬度转换成两列数据
 * @author HuangAnting
 * @date 2022/4/12 17:26
*/
public class CustomRowWriteHandler implements RowWriteHandler {

    /**
     * 序号的样式，与其他列保持一样的样式
     */
    private CellStyle firstCellStyle;
    private static final String LON_CELL_NAME = "经度";
    private static final String LAT_CELL_NAME = "纬度";

    /**
     * 列号
     */
    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer integer, Boolean isHead) {
        Cell cell = row.getCell(4);
        row.removeCell(cell);
        Cell lon = row.createCell(4);
        Cell lat = row.createCell(5);
        if (!isHead) {
            String stringCellValue = cell.getStringCellValue();
            try {
                MonPoint monPoint = JSONObject.parseObject(stringCellValue, MonPoint.class);
                lon.setCellValue(monPoint.getLon());
                lat.setCellValue(monPoint.getLat());
            }
            catch (Exception e){
            }
        }else {
            Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
            firstCellStyle = firstCellStyle(workbook);
            lon.setCellStyle(firstCellStyle);
            lat.setCellStyle(firstCellStyle);
            lon.setCellValue(LON_CELL_NAME);
            lat.setCellValue(LAT_CELL_NAME);
        }
    }

    /**
     * excel首列序号列样式
     *
     * @param workbook
     * @return
     */
    public CellStyle firstCellStyle(Workbook workbook) {
        CellStyle cellStyle = workbook.createCellStyle();
        //居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 灰色
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        //设置边框
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        //文字
        Font font = workbook.createFont();
        font.setBold(Boolean.TRUE);
        cellStyle.setFont(font);
        return cellStyle;
    }
}
